package cn.chiship.framework.third.biz.wxpub.controller;

import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.framework.third.biz.wxpub.pojo.dto.BasicMaterialsDto;
import cn.chiship.framework.third.core.common.MaterialsTypeEnum;
import cn.chiship.framework.third.core.common.ThirdUtil;
import cn.chiship.framework.third.core.enums.ThirdContentStatusEnum;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.annotation.NoParamsSign;
import cn.chiship.sdk.framework.base.BaseService;
import cn.chiship.sdk.framework.base.BaseController;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.annotation.Authorization;

import javax.annotation.Resource;

import cn.chiship.framework.third.biz.wxpub.service.ThirdWechatArticleService;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatArticle;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatArticleExample;
import cn.chiship.framework.third.biz.wxpub.pojo.dto.ThirdWechatArticleDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 文章素材控制层 2022/7/13
 *
 * @author lijian
 */
@RestController
@RequestMapping("/thirdWechatArticle")
@Api(tags = "文章素材")
public class ThirdWechatArticleController extends BaseController<ThirdWechatArticle, ThirdWechatArticleExample> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThirdWechatArticleController.class);

    @Resource
    private ThirdWechatArticleService thirdWechatArticleService;

    @Override
    public BaseService getService() {
        return thirdWechatArticleService;
    }

    @SystemOptionAnnotation(describe = "文章素材分页")
    @ApiOperation(value = "文章素材分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", defaultValue = "10", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "resourceType", value = "类型", required = true, dataTypeClass = Byte.class, paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态  0:草稿 1:未发布 2:已发布 3:回收站", dataTypeClass = Byte.class, paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "文章分类", dataTypeClass = Byte.class, paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "标题", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "author", value = "作者", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "发布时间", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "发布结束时间", dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "isDeleted", value = "是否物理删除", dataTypeClass = Byte.class, paramType = "query")

    })
    @GetMapping(value = "/page")
    public ResponseEntity<BaseResult> page(
            @RequestParam(required = false, defaultValue = "", value = "keyword") String keyword,
            @RequestParam(required = false, defaultValue = "", value = "categoryId") String categoryId,
            @RequestParam(required = false, value = "status") Byte status,
            @RequestParam(value = "resourceType") Byte resourceType,
            @RequestParam(required = false, value = "isDeleted") Byte isDeleted,
            @RequestParam(required = false, defaultValue = "", value = "author") String author,
            @RequestParam(required = false, defaultValue = "", value = "startDate") Long startDate,
            @RequestParam(required = false, defaultValue = "", value = "endDate") Long endDate) {
        ThirdWechatArticleExample thirdWechatArticleExample = new ThirdWechatArticleExample();
        // 创造条件
        ThirdWechatArticleExample.Criteria thirdWechatArticleCriteria = thirdWechatArticleExample.createCriteria();
        thirdWechatArticleCriteria.andResourceTypeEqualTo(resourceType).andAppIdEqualTo(ThirdUtil.getAppId());
        if (!StringUtil.isNullOrEmpty(keyword)) {
            if (MaterialsTypeEnum.BASIC_MATERIALS_TYPE_TEXT.getType().equals(resourceType)) {
                thirdWechatArticleCriteria.andSummaryLike("%" + keyword + "%");
            } else {
                thirdWechatArticleCriteria.andTitleLike("%" + keyword + "%");
            }
        }
        if (!StringUtil.isNullOrEmpty(categoryId)) {
            thirdWechatArticleCriteria.andCategoryIdEqualTo(categoryId);
        }
        if (!StringUtil.isNull(status)) {
            thirdWechatArticleCriteria.andStatusEqualTo(status);
        }
        if (!StringUtil.isNull(isDeleted)) {
            thirdWechatArticleCriteria.andIsDeletedEqualTo(isDeleted);
        }
        if (!StringUtil.isNullOrEmpty(author)) {
            thirdWechatArticleCriteria.andAuthorLike(author + "%");
        }
        if (!StringUtil.isNull(startDate)) {
            thirdWechatArticleCriteria.andPublishDateGreaterThanOrEqualTo(endDate);
        }
        if (!StringUtil.isNull(endDate)) {
            thirdWechatArticleCriteria.andPublishDateLessThanOrEqualTo(endDate);
        }

        return super.responseEntity(BaseResult.ok(super.page(thirdWechatArticleExample)));
    }

    @SystemOptionAnnotation(describe = "文章素材列表数据")
    @ApiOperation(value = "文章素材列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "关键字", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "resourceType", value = "类型", required = true, dataTypeClass = Byte.class, paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态 1 未发布 2 已发布 0 草稿箱", dataTypeClass = Byte.class, paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "文章分类", dataTypeClass = Byte.class, paramType = "query"),})
    @GetMapping(value = "/list")
    public ResponseEntity<BaseResult> list(
            @RequestParam(required = false, defaultValue = "", value = "keyword") String keyword,
            @RequestParam(required = false, defaultValue = "", value = "categoryId") String categoryId,
            @RequestParam(required = false, value = "status") Byte status,
            @RequestParam(value = "resourceType") Byte resourceType) {
        ThirdWechatArticleExample thirdWechatArticleExample = new ThirdWechatArticleExample();
        // 创造条件
        ThirdWechatArticleExample.Criteria thirdWechatArticleCriteria = thirdWechatArticleExample.createCriteria();
        thirdWechatArticleCriteria.andIsDeletedEqualTo(BaseConstants.NO).andResourceTypeEqualTo(resourceType)
                .andAppIdEqualTo(ThirdUtil.getAppId());
        if (!StringUtil.isNullOrEmpty(keyword)) {
            if (MaterialsTypeEnum.BASIC_MATERIALS_TYPE_TEXT.getType().equals(resourceType)) {
                thirdWechatArticleCriteria.andSummaryLike("%" + keyword + "%");
            } else {
                thirdWechatArticleCriteria.andTitleLike("%" + keyword + "%");
            }
        }
        if (!StringUtil.isNullOrEmpty(categoryId)) {
            thirdWechatArticleCriteria.andCategoryIdEqualTo(categoryId);
        }
        if (!StringUtil.isNull(status)) {
            thirdWechatArticleCriteria.andStatusEqualTo(status);
        }
        return super.responseEntity(BaseResult.ok(super.list(thirdWechatArticleExample)));
    }

    @ApiOperation(value = "文章预览")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path", required = true)})
    @GetMapping(value = "/view/{id}")
    public ResponseEntity<BaseResult> view(HttpServletRequest request, @PathVariable("id") String id) {
        CacheUserVO cacheUserVO = null;
        try {
            cacheUserVO = getLoginUser();
        } catch (RuntimeException e) {
            System.out.println("捕获令牌失效错误，不让前端对这个错误处理");
        }
        return super.responseEntity(thirdWechatArticleService.view(request, id, cacheUserVO));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_SAVE, describe = "保存文章素材")
    @ApiOperation(value = "保存文章素材")
    @PostMapping(value = "save")
    @Authorization
    public ResponseEntity<BaseResult> save(@RequestBody @Valid ThirdWechatArticleDto thirdWechatArticleDto) {
        ThirdWechatArticle thirdWechatArticle = new ThirdWechatArticle();
        BeanUtils.copyProperties(thirdWechatArticleDto, thirdWechatArticle);
        return super.responseEntity(super.save(thirdWechatArticle));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_SAVE, describe = "保存基本素材(文本、视频、音频、图片)")
    @ApiOperation(value = "保存基本素材")
    @PostMapping(value = "saveBasic")
    @NoParamsSign
    @Authorization
    public ResponseEntity<BaseResult> saveBasic(@Valid BasicMaterialsDto basicMaterialsDto,
                                                @RequestParam(required = false, value = "file") MultipartFile file) {
        return super.responseEntity(thirdWechatArticleService.saveBasic(basicMaterialsDto, file, getLoginUser()));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE, describe = "更新文章素材")
    @ApiOperation(value = "更新文章素材")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path",
            required = true)})
    @PostMapping(value = "update/{id}")
    @Authorization
    public ResponseEntity<BaseResult> update(@PathVariable("id") String id,
                                             @RequestBody @Valid ThirdWechatArticleDto thirdWechatArticleDto) {
        ThirdWechatArticle thirdWechatArticle = new ThirdWechatArticle();
        BeanUtils.copyProperties(thirdWechatArticleDto, thirdWechatArticle);
        return super.responseEntity(super.update(id, thirdWechatArticle));
    }


    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "删除文章素材")
    @ApiOperation(value = "删除文章素材")
    @PostMapping(value = "remove")
    @Authorization
    public ResponseEntity<BaseResult> remove(@RequestBody(required = true) List<String> ids) {
        ThirdWechatArticleExample thirdWechatArticleExample = new ThirdWechatArticleExample();
        thirdWechatArticleExample.createCriteria().andIdIn(ids);
        return super.responseEntity(super.remove(thirdWechatArticleExample));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "文章发布")
    @ApiOperation(value = "文章发布")
    @PostMapping(value = "release")
    @Authorization
    public ResponseEntity<BaseResult> release(@RequestBody @Valid List<String> ids) {
        if (ids.isEmpty()) {
            return super.responseEntity(BaseResult.error("集合不能为空！"));
        }
        return super.responseEntity(
                thirdWechatArticleService.changeStatus(ids, ThirdContentStatusEnum.CONTENT_STATUS_PUBLISHED));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "文章撤销发布")
    @ApiOperation(value = "文章撤销发布")
    @PostMapping(value = "revokePublication")
    @Authorization
    public ResponseEntity<BaseResult> revokePublication(@RequestBody @Valid List<String> ids) {
        if (ids.isEmpty()) {
            return super.responseEntity(BaseResult.error("集合不能为空！"));
        }
        return super.responseEntity(thirdWechatArticleService.changeStatus(ids, ThirdContentStatusEnum.CONTENT_STATUS_RELEASED));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "文章从回收站恢复")
    @ApiOperation(value = "文章从回收站恢复")
    @PostMapping(value = "recovery")
    @Authorization
    public ResponseEntity<BaseResult> recovery(@RequestBody @Valid List<String> ids) {
        if (ids.isEmpty()) {
            return super.responseEntity(BaseResult.error("集合不能为空！"));
        }
        return super.responseEntity(thirdWechatArticleService.recovery(ids));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "文章移入回收站")
    @ApiOperation(value = "文章移入回收站")
    @PostMapping(value = "moveRecycleBin")
    @Authorization
    public ResponseEntity<BaseResult> moveRecycleBin(@RequestBody @Valid List<String> ids) {
        if (ids.isEmpty()) {
            return super.responseEntity(BaseResult.error("集合不能为空！"));
        }
        return super.responseEntity(thirdWechatArticleService.moveRecycleBin(ids));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE, describe = "文章设置是否允许评论")
    @ApiOperation(value = "文章设置是否允许评论")
    @PostMapping(value = "setAllowComment/{id}")
    @Authorization
    public ResponseEntity<BaseResult> setAllowComment(@PathVariable("id") String id, @RequestBody @Valid Boolean allow) {
        return super.responseEntity(thirdWechatArticleService.setAllowComment(id, allow));
    }


    @ApiOperation(value = "加载上一篇及下一篇")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "文章ID", required = true, dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "频道（all或空：所有栏目）", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "isAll", value = "是否加载所有）", dataTypeClass = Boolean.class, paramType = "query"),

    })
    @GetMapping(value = "findPreAndNext")
    public ResponseEntity<BaseResult> findPreAndNext(@RequestParam(value = "id") String id,
                                                     @RequestParam(value = "isAll", required = false) Boolean isAll,
                                                     @RequestParam(value = "categoryId", required = false) String categoryId) {
        return super.responseEntity(thirdWechatArticleService.findPreAndNext(id, categoryId, isAll));
    }

}
